package com.mingqijia.gassafety.job.job.warnStrategy;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.job.service.ConsumerServiceInfoService;
import com.mingqijia.gassafety.job.service.impl.EquipmentServiceImpl;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.enums.YesNoEnum;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;

/**
 * @author mby
 * @version 1.0.0
 * @ClassName CreateServiceInfoHistoryJob.java
 * @Description TODO
 * @createTime 2024年01月16日
 */
@Component
@Slf4j
public class CreateServiceInfoHistoryJob {

    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    ConsumerMapper consumerMapper;
    @Autowired
    WorkOrderHistoryMapper workOrderHistoryMapper;
    @Autowired
    EquipmentServiceImpl equipmentService;
    @Autowired
    ConsumerServiceInfoService consumerServiceInfoService;

    public static final Integer pageSize = 1000;

    /**
     *   生成历史的服务信息，生产设备目前一万八，已绑定客户的八千，执行一次后删除
     */
    @XxlJob("createServiceInfoHistoryJob")
    public ReturnT<String> createServiceInfoHistoryJob(String param) {
        XxlJobLogger.log("XXLJOB-createServiceInfoHistoryJob start..." );
        log.info("createServiceInfoHistoryJob--start--------");
        String key = Constants.EQUIPMENT_CREATE_SERVICE_INFO;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    execute();
                    return ReturnT.SUCCESS;
                } catch (Exception e) {
                    log.info("createServiceInfoHistoryJob-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("createServiceInfoHistoryJob-error:{}", e);
        }
        log.info("createServiceInfoHistoryJob--end--------");
        XxlJobLogger.log("XXLJOB-createServiceInfoHistoryJob end..." );
        return ReturnT.SUCCESS;
    }

    private boolean execute() {
        //查询所有用户
        int pageIndex = 1;
        long total = 0;
        Map<Integer, String> consumerIndustryMap = new HashMap<>();
        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        do{
            Page<Consumer> pages = PageHelper.startPage(pageIndex, pageSize);
            List<Consumer> consumers = consumerMapper.selectList(consumerWrapper);
            pageIndex++;
            total = pages.getTotal();
            if (CollectionUtils.isNotEmpty(consumers)) {
                consumers.stream().forEach(x -> {
                    consumerIndustryMap.put(x.getId(),x.getIndustryType());
                });
            }
        }while(total > (pageIndex - 1) * pageSize);
        // 安装工单，维修工单,数据库总共大概1000条数据
        Map<String, Integer> orderTypeMap = new HashMap<>();
        LambdaQueryWrapper<WorkOrderHistory> workOrderHistoryWrapper = new LambdaQueryWrapper<>();
        workOrderHistoryWrapper.eq(WorkOrderHistory::getHandleStatus, 1).eq(WorkOrderHistory::getIsDeleted, IS_DELETED_FALSE)
                .orderByAsc(WorkOrderHistory::getUpdatedAt);
        List<WorkOrderHistory> workOrderHistories = workOrderHistoryMapper.selectList(workOrderHistoryWrapper);
        if (CollectionUtils.isNotEmpty(workOrderHistories)) {
            workOrderHistories.stream().forEach(x -> {
                orderTypeMap.put(x.getDeviceId(),x.getOrderType());
            });
        }
        //查询所有绑定中的设备
        int dtuPageIndex = 1;
        long dtuTotal = 0;
        QueryWrapper<Dtu> dtuWrapper = new QueryWrapper<>();
        dtuWrapper.lambda().eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .gt(Dtu::getConsumerId, 0);
        do{
            Page<Dtu> pages = PageHelper.startPage(dtuPageIndex, pageSize);
            List<Dtu> equipmentList = equipmentService.list(dtuWrapper);
            dtuPageIndex++;
            dtuTotal = pages.getTotal();
            List<ConsumerServiceInfo> consumerServiceInfos = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(equipmentList)) {

                equipmentList.stream().forEach(dtu -> {
                    // 过滤测试环境脏数据，删除的客户也有设备的脏数据
                    if (!dtu.getEquipmentType().equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode()) && consumerIndustryMap.get(dtu.getConsumerId()) != null) {
                        ConsumerServiceInfo service = new ConsumerServiceInfo();
                        service.setId(null);
                        service.setConsumerId(dtu.getConsumerId());
                        service.setIndustryType(consumerIndustryMap.get(dtu.getConsumerId()) == null ? "" : consumerIndustryMap.get(dtu.getConsumerId()));
                        service.setImei(dtu.getIMEI());
                        try {
                            service.setStartDate(StringUtils.isNotEmpty(dtu.getInstallDate()) ? DateUtils.toDate(dtu.getInstallDate()) : DateUtils.today());
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        if (EquipmentType.HOME_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType())){
                            service.setEndDate(DateUtils.getDiffYearDate(service.getStartDate(), 5));
                        } else {
                            // 工商业报警器
                            service.setEndDate(DateUtils.getDiffYearDate(service.getStartDate(), 3));
                        }
                        service.setRemark(new StringBuilder().append("设备号：").append(dtu.getIMEI())
                                .append("安装日期：").append(dtu.getInstallDate()).append("当前状态：关联").toString());
                        service.setIsDeleted(YesNoEnum.N.isFlag());
                        service.setCreatedAt(new Date());
                        service.setUpdatedAt(service.getCreatedAt());
                        service.setSpId(dtu.getSpId());
                        if (orderTypeMap.get(service.getImei()) != null && orderTypeMap.get(service.getImei()) == 3) {
                            // 维修工单
                            service.setIsUpdate(1);
                        } else {
                            service.setIsUpdate(0);
                        }
                        service.setIsSend(0);
                        consumerServiceInfos.add(service);
                    }
                });
            }
            if (CollectionUtils.isNotEmpty(consumerServiceInfos)) {
                consumerServiceInfoService.saveBatch(consumerServiceInfos);
            }
        }while(dtuTotal > (dtuPageIndex - 1) * pageSize);


        return true;
    }



}